import { LeftOutlined, CheckCircleOutlined } from '@ant-design/icons'
import c from 'classnames'
import { Actionable } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { WarnItem } from '@/services/contact-chat'
import type { ExternalContact, GroupContact, InternalContact } from '@/services/contact-types/'
import type { QywxInfo } from '@/services/qywxs'
import './warn-items.module.less'

export default function WarnItems(props: { onClose: () => void }) {
  const { onClose } = props

  const [
    warns,
    warnTotalCount,
    externals,
    receivedTransfers,
    groups,
    internals,
    qywxs,
    currentContactId,
  ] = useStreams(
    services.chat.metas.warns,
    services.chat.metas.warnTotalCount,
    services.externals.list,
    services.transfers.receiveList,
    services.groups.list,
    services.internals.list,
    services.qywxs.usables,
    services.contacts.current.id,
  )

  // 进入和退出此列表时，都重置“当前联系人”
  useEffect(() => {
    services.contacts.current.cancel()
    return () => services.contacts.current.cancel()
  }, [])

  const choose = useCallback((item: WarnItem) => {
    services.chat.inProgress.markWithFocus(item.contactId, item.firstMsgId)
  }, [])

  const warnList = useMemo(() => [...warns.values()], [warns])

  const getItemContact = useCallback(
    (item: WarnItem) => {
      if (receivedTransfers.has(item.contactId)) {
        const contact = receivedTransfers.get(item.contactId)!
        return { contact, qywx: { friendlyFullName: contact.transfer.fromName } }
      }

      const contact =
        externals.get(item.contactId) ?? groups.get(item.contactId) ?? internals.get(item.contactId)
      if (contact) {
        const qywx = qywxs.get(contact.ownerWxid)
        if (qywx) return { contact, qywx }
      }

      return { contact: null, qywx: null }
    },
    [externals, receivedTransfers, groups, internals, qywxs],
  )

  return <div styleName="wrap">
    <header>
      <span styleName="back" onClick={onClose}>
        <LeftOutlined />
        <span>返回</span>
      </span>

      <span styleName="total-count">预警消息（{warnTotalCount}）</span>
    </header>

    <div styleName="list">
      {warnList.map(item => {
        const { contact, qywx } = getItemContact(item)
        if (!contact) return null
        return <Item
          key={item.contactId}
          item={item}
          isCurrent={currentContactId === item.contactId}
          contact={contact}
          qywx={qywx}
          choose={choose}
        />
      })}
    </div>
  </div>
}

function Item(props: {
  item: WarnItem
  isCurrent: boolean
  contact: ExternalContact | GroupContact | InternalContact
  qywx: Pick<QywxInfo, 'friendlyFullName'>
  choose: (item: WarnItem) => void
}) {
  const { item, isCurrent, contact, qywx, choose } = props

  const done = useCallback(
    (event: React.MouseEvent<HTMLSpanElement>) => {
      event.stopPropagation()
      void services.chat.metas.doneWarn(contact.id, contact.conversationId)
    },
    [contact],
  )

  return <div styleName={c('warn-item', isCurrent && 'current')} onClick={() => choose(item)}>
    <img styleName="avatar" loading="lazy" src={contact.avatar || defaultAvatar} />
    <div styleName="info">
      <div styleName="name">
        {contact.remark ? (
          <>
            {contact.remark}
            <span styleName="tip-name ">{contact.name}</span>
          </>
        ) : (
          contact.name
        )}
      </div>
      <div styleName="owner-name">{qywx.friendlyFullName}</div>
      <div styleName="matches">预警：{item.matchRules.map(v => `「${v}」`).join('')}</div>
    </div>
    <Actionable>
      <div styleName="done" onClick={done}>
        <CheckCircleOutlined />
        <span>已处理</span>
      </div>
    </Actionable>
  </div>
}
